package com.hainatong.shiphelper.module.holiday.fragment;

import android.os.Bundle;
import android.view.View;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hainatong.shiphelper.GlobalConfig;
import com.hainatong.shiphelper.MvvmLazyFragment;
import com.hainatong.shiphelper.R;
import com.hainatong.shiphelper.databinding.FragmentCantJobBinding;
import com.hainatong.shiphelper.mainhome.adapter.ProcessStepAdapter;
import com.hainatong.shiphelper.module.holiday.PortActivity;
import com.hainatong.shiphelper.module.holiday.entity.PortBean;
import com.hainatong.shiphelper.module.holiday.entity.VacationParam;
import com.hainatong.shiphelper.module.holiday.viewmodel.VacationViewModel;
import com.hainatong.shiphelper.module.workermgr.WorkerMgrActivity;
import com.hainatong.shiphelper.module.workermgr.entity.WorkerBean;
import com.hainatong.shiphelper.module.workermgr.fragment.WorkerFragment;
import com.hainatong.shiphelper.utils.ComDataUtils;
import com.hainatong.shiphelper.utils.GsonUtil;
import com.hainatong.shiphelper.utils.PushToast;
import com.hainatong.shiphelper.utils.TimeUtil;
import com.hainatong.shiphelper.widget.LoadingDialog;
import com.hainatong.shiphelper.widget.PickerDialog;
import com.hainatong.shiphelper.widget.datapicker.CustomDatePicker;
import com.jeremyliao.liveeventbus.LiveEventBus;


/**
 *  不能 适岗
 */
public class FireWorkerFragment extends MvvmLazyFragment<FragmentCantJobBinding, VacationViewModel>
{

    private static String FIRE_WORK_TAG = "FireWorkerFragment";

    public static String FIRE_USER_TAG = "FireUserResult";

    private int timeTag = 0;
    private CustomDatePicker datePicker;
    private PickerDialog pickerDialog;
    //选择的  港口
    private PortBean selectPort;
    //从 人员管理 来的 不能试岗的 员工
    private WorkerBean fireWorker;
    private VacationParam vacParam;

    private LoadingDialog loading;

    public static FireWorkerFragment newInstance(String typeCode)
    {
        Bundle bundle = new Bundle();
        bundle.putString( FIRE_WORK_TAG , typeCode );
        FireWorkerFragment holidayFragment = new FireWorkerFragment();
        holidayFragment.setArguments( bundle );
        return holidayFragment;
    }

    @Override
    public int getLayoutId()
    {
        return R.layout.fragment_cant_job;
    }

    @Override
    public int getBindingVariable()
    {
        return 0;
    }

    @Override
    protected void initParameters()
    {
        Bundle args = getArguments();
        String type = "";
        if(  args != null )
        {
            type = args.getString(FIRE_WORK_TAG , "");
        }

        if( !StringUtils.isEmpty( type ))
        {
            vacParam = GsonUtil.json2Obj( type, VacationParam.class);
        }
    }

    @Override
    protected void onRetryBtnClick()
    {
    }

    @Override
    protected void initView(View view)
    {
        // vacParam 从前一个页面 传过来
        //vacParam = new VacationParam();

        loading = new LoadingDialog( getActivity(), getString( R.string.loading ) );
        pickerDialog = new PickerDialog(getActivity(), (selectStr, position) -> {
            //viewDataBinding.tvArea.setText( selectStr );
            //ToastUtils.showShort( selectStr );
        });
        initDataPicker();
        // 选worker
        viewDataBinding.btnSelectWorker.setOnClickListener(v -> {
            // 通知 开始 选 用户
            LiveEventBus.get(WorkerFragment.SELECT_WORKER_TAG ,Boolean.class ).post( true );
            WorkerMgrActivity.start( getActivity() );
        });
        // 选开始时间
        viewDataBinding.btnSelectStartTime.setOnClickListener(v -> {
            timeTag = 1;
            datePicker.show( TimeUtil.getTimeStandard( System.currentTimeMillis() ) );
        });
        // 选结束时间
        viewDataBinding.btnSelectEndTime.setOnClickListener( v -> {
            timeTag = 2;
            datePicker.show( TimeUtil.getTimeStandard( System.currentTimeMillis() ) );
        } );

        // 选港口
        viewDataBinding.btnSelectPort.setOnClickListener( v -> {

            //pickerDialog.showPickContent(new String[]{"泉州港","海口港","上海港","天津港"});

            PortActivity.start( getActivity() );

        } );

        ProcessStepAdapter stepAdapter = ProcessStepAdapter.newInstance( new String[]{"审批人","审批人","审批人"}, new String[]{"大副","船长","岸基"} );
        viewDataBinding.stepRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        viewDataBinding.stepRecyclerview.hasFixedSize();
        viewDataBinding.stepRecyclerview.setAdapter( stepAdapter );

        // 提交 不能试岗 申请
        viewDataBinding.btnSubmit.setOnClickListener(v -> {

            int totalHours = 0;
            String startTime = viewDataBinding.tvStartTime.getText().toString();
            String endTime = viewDataBinding.tvEndTime.getText().toString();

            boolean isTimeRight = ComDataUtils.isEndTimeRight( startTime ,endTime );
            if( !isTimeRight )
            {
                ToastUtils.showShort("选择正确的日期");
                return;
            }
            totalHours = ComDataUtils.getHolidayHoursCount(startTime , endTime);

            vacParam.setCreator( GlobalConfig.getInstance().getUserInfo().getUserTrueName());
            vacParam.setCreateID( GlobalConfig.getInstance().getUserInfo().getUuid() );

            String remarkStr = viewDataBinding.etHolidayReason.getText().toString();
            vacParam.setRemark( remarkStr );
            LogUtils.e("totalHours  = " + totalHours);
            // 设置 请假的 总 小时数
            vacParam.setTotal(totalHours);
            vacParam.setStatus("1");

            loading.show();
            viewModel.applyUserVacation(vacParam);

        });
        LiveEventBus.get(WorkerFragment.SELECT_WORKER_TAG ,WorkerBean.class )
                .observeSticky( this , theWorker -> {
                    setFireWorkerInfo(theWorker);
                } );
        LiveEventBus.get(FIRE_USER_TAG, WorkerBean.class)
                .observeSticky( this , theWorker -> {
                    setFireWorkerInfo(theWorker);
                } );


        LiveEventBus.get(PortActivity.PORT_RESULT , PortBean.class)
                .observeSticky( this , portBean -> {
                    // 获取到 港口 信息
                    selectPort = portBean;

                    viewDataBinding.tvArea.setText( selectPort.getName() );
                    //设置 港口
                    vacParam.setPort( selectPort.getName());
                    //"b26c428e-863b-11eb-b45c-5254006b78b4"
                    vacParam.setPort_id( selectPort.getUuid() );

                } );

    }

    private void initDataPicker()
    {
        datePicker = new CustomDatePicker(getActivity(), new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time)
            {
                // 时间 精确到 分
                if( timeTag == 1 )
                {
                    // 开始时间
                    String startDate =  time ;
                    viewDataBinding.tvStartTime.setText( startDate  );
                    vacParam.setStartdate( startDate );

                }
                else
                {
                    String endDate =  time ;
                    viewDataBinding.tvEndTime.setText(endDate);
                    vacParam.setEnddate(endDate);
                }

                // 获取时间 一个long值
                //long resultTime = TimeUtil.parseDate(time).getTime();
                LogUtils.e("CustomDatePicker", time + "  时间= " + TimeUtil.getTimeYMDHS2YMD( time ));
            }
        } , CustomDatePicker.getTimeStandard(System.currentTimeMillis()),TimeUtil.getTimeStandard((System.currentTimeMillis() + 1000*60*60*24*365*10)));

        // 初始化日期格式请用：yyyy-MM-dd HH:mm
        // HH:mm，否则不能正常运行 //false 不显示时和分
        datePicker.showSpecificTime(true);
        datePicker.setIsLoop(true); // false 不允许循环滚动
        /*
         * //currentTime.setText(now); datePicker = new CustomDatePicker(this, new
         * CustomDatePicker.ResultHandler() {
         * @Override public void handle(String time) { // 回调接口，获得选中的时间 //currentTime.setText(time);
         * } }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
         * datePicker.showSpecificTime(true); // 显示时和分 datePicker.setIsLoop(true); // 允许循环滚动
         */
    }


    @Override
    protected void lazyLoad()
    {

        // 申请 结果
        viewModel.getVacApplyResult().observe( this , result -> {
            loading.hide();
            if( result.isSuccess() )
            {
                PushToast.getInstance(getActivity()).show( PushToast.SUBMIT_SUCCESS );
                getActivity().finish();
            }
            else
            {
                ToastUtils.showShort( result.getMsg() );
            }
        } );

    }

    private void setFireWorkerInfo(WorkerBean theWorker)
    {
        // 获取到 港口 信息
        fireWorker = theWorker;
        viewDataBinding.tvWorkerName.setText( fireWorker.getUserTrueName());
        //设置 离职人员信息
        vacParam.setFireWorkerInfo(fireWorker );
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        loading.dismiss();
    }
}
